package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.Logs;
import com.hjj.springboot.entity.PageBean;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.service.ILogsService;
import com.hjj.springboot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/logs")
public class AdminLogsController {

    @Autowired
    private ILogsService logsService;

//    删除
    @SystemLogs(operation = "系统日志",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id) {
        logsService.removeById(id);
        return R.ok();
    }
//    批量删除
    @SystemLogs(operation = "系统日志",type = LogType.BATCH_DELETE)
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        logsService.removeByIds(ids);
        return R.ok();
    }
//    查询
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean) {
        String query=pageBean.getQuery().trim();
        Page<Logs> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Logs> pageResult = logsService.page(page,new QueryWrapper<Logs>().like(StringUtil.isNotEmpty(query),"operation",query).orderByDesc("id"));
        Map<String, Object> map = new HashMap<>();
        map.put("total", pageResult.getTotal());
        map.put("logsList", pageResult.getRecords());
        return R.ok(map);
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("系统日志", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Logs> logsList = logsService.list(new QueryWrapper<Logs>().like(StringUtil.isNotEmpty(queryStr),"operation",query));
        EasyExcel.write(response.getOutputStream(),Logs.class)
                .sheet("系统日志")
                .doWrite(logsList);
    }


}
